<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="boiler-control">
      <Row :gutter="16">
        <Col v-for="(boiler, index) in boilers" :key="index" span="4">
          <Card class="boiler-card">
            <div slot="title" class="title-container">
              <div class="title-text">锅炉{{ index + 1 }}号</div>
            </div>
            <div
              class="status-content"
              :style="{
                minHeight: boiler.status === 'fault' ? '180px' : '140px'
              }"
            >
              <div class="status-tag">
                <span>通讯状态：</span>
                <Icon
                  type="md-radio-button-on"
                  :color="
                    boiler.communicationStatus.value ? '#19be6b' : '#ed4014'
                  "
                  size="14"
                />
                <span class="status-text">{{
                  boiler.communicationStatus.value ? '离线' : '在线'
                }}</span>
              </div>
              <p>本机状态： {{ statusMap[boiler.status.value] }}</p>

              <div class="status-details">
                <div class="feed-pump-control">
                  <div>给水泵控制：</div>
                  <ButtonGroup>
                    <Button type="info" @click="handleFeedPumpAuto(index)">
                      自动(102)
                    </Button>
                    <Button type="warning" @click="handleFeedPumpManual(index)">
                      手动(103)
                    </Button>
                  </ButtonGroup>
                  <ButtonGroup>
                    <Button
                      type="primary"
                      @click="handleFeedPumpStart(index)"
                      :disabled="boiler.feedPump.mode.value !== 103"
                    >
                      启动(100)
                    </Button>
                    <Button
                      type="error"
                      @click="handleFeedPumpStop(index)"
                      :disabled="boiler.feedPump.mode.value !== 103"
                    >
                      停止(101)
                    </Button>
                  </ButtonGroup>
                </div>

                <div class="sensor-status">
                  <div
                    v-for="(sensor, key) in boiler.sensors"
                    :key="key"
                    class="sensor-item"
                  >
                    <span>{{ sensorMap[key] }}：</span>
                    <Tag :color="sensor.value ? 'red' : 'green'">
                      {{ sensor.value ? '闭合' : '断开' }}
                    </Tag>
                  </div>
                </div>
              </div>

              <ButtonGroup class="btn-group">
                <Button type="primary" @click="handleStart(index)">
                  启动
                </Button>
                <Button type="error" @click="handleStop(index)">
                  停止
                </Button>
                <Button type="warning" @click="handleReset(index)">
                  复位
                </Button>
                <Button type="info" @click="handleMute(index)">
                  消音
                </Button>
              </ButtonGroup>
            </div>
          </Card>
        </Col>
      </Row>

      <!-- 蒸汽补水表单 -->
      <div class="quadrant-title">蒸汽补水</div>
      <Card class="table">
        <Form :label-width="150" label-position="left" class="grid-form">
          <FormItem label="蒸汽回收桶电导率上限" class="form-item">
            <InputNumber
              v-model="steamForm.conductivityUpper.value"
              :min="0"
              :max="32000"
              @on-blur="handleSteamBlur('conductivityUpper')"
            />
          </FormItem>
          <FormItem label="回汽电导率" class="form-item">
            <InputNumber v-model="steamForm.conductivity.value" readonly />
          </FormItem>
          <FormItem label="手动加水设时" class="form-item">
            <InputNumber
              v-model="steamForm.manualWaterTime.value"
              :min="0"
              :max="600"
              @on-blur="handleSteamBlur('manualWaterTime')"
            />
          </FormItem>
          <FormItem label="手动加水计时" class="form-item">
            <InputNumber
              v-model="steamForm.manualWaterTimer.value"
              :min="0"
              :max="600"
              @on-blur="handleSteamBlur('manualWaterTimer')"
            />
          </FormItem>
          <FormItem label="蒸汽补水箱阀自动开关" class="form-item">
            <i-switch
              size="large"
              v-model="steamForm.autoSwitch.value"
              @on-change="
                handleSteamSwitchChange(steamForm.autoSwitch, 'autoSwitch')
              "
            >
              <span slot="open">手动</span>
              <span slot="close">自动</span>
            </i-switch>
          </FormItem>
          <FormItem label="蒸汽补水箱阀开关" class="form-item">
            <i-switch
              size="large"
              v-model="steamForm.valveSwitch.value"
              :disabled="!steamForm.autoSwitch.value"
              @on-change="
                handleSteamSwitchChange(steamForm.valveSwitch, 'valveSwitch')
              "
            >
              <span slot="open">开</span>
              <span slot="close">关</span>
            </i-switch>
          </FormItem>
          <FormItem label="蒸汽回水切换阀" class="form-item">
            <i-switch
              v-model="steamForm.returnWaterSwitch.value"
              @on-change="
                handleSteamSwitchChange(
                  steamForm.returnWaterSwitch,
                  'valveSwitch'
                )
              "
            >
              <span slot="open">开</span>
              <span slot="close">关</span>
            </i-switch>
          </FormItem>
        </Form>
      </Card>
    </div>
  </div>
</template>

<script lang="ts">
import {
  Tsrv,
  T_srv,
  ifs,
  ts,
  vue,
  I_cmd,
  T_cmd,
  steamForm,
  boilers,
  N_BoilerMonitor
} from './config';

@T_srv.comp
export default class cBoilerControl extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  /* 组件名 */
  private name: string = 'cBoilerControl';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  /* 遮罩 */
  public isMask: boolean = false;

  public steamForm: N_BoilerMonitor.SteamForm = steamForm();

  public ecDetCodes: string[] = [];

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.GT_command.startTask();
  }

  destroyed() {
    this.GT_command.stopTask();
    /* 注册组件销毁 */
    this.$bus.$off('__PLC_CONNSTATE__');
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }

  private receiveEvent() {
    this.$bus.$on(
      '__PLC_CONNSTATE__',
      (data: { connState: boolean; ecBoxName: string }) => {
        if (data.ecBoxName === 'mianyang') {
          if (data.connState) {
            if (!this.GT_command.isOpenTask) {
              this.GT_command.startTask();
            }
          } else {
            this.GT_command.stopTask();
          }
        }
      }
    );
  }

  /* 设置组件整体遮罩 */
  public setMask(p: boolean) {
    this.isMask = p;
  }

  public getMask(p: boolean): boolean {
    return this.isMask;
  }

  private statusMap = {
    0: '待机',
    1: '故障',
    2: '运行中'
  };

  private sensorMap = {
    lowLimitWaterLevel: '低限水位',
    lowWaterLevel: '低水位',
    highWaterLevel: '高水位',
    highWaterAlarm: '高水位报警',
    wallOverTemp: '壁温过高',
    startStopControl: '启停控制',
    overPressureAlarm: '超压报警'
  };

  public boilers: N_BoilerMonitor.BoilerState[] = boilers();

  private init() {
    this.ecDetCodes = [];
    this.boilers.forEach(boiler => {
      // 获取所有点位
      Object.keys(boiler).forEach(key => {
        if (
          key === 'controlButtons' ||
          key === 'feedPump' ||
          key === 'sensors'
        ) {
          Object.keys(boiler[key]).forEach(code => {
            this.ecDetCodes.push(boiler[key][code].code);
          });
        } else {
          this.ecDetCodes.push(boiler[key].code);
        }
      });
    });

    Object.keys(this.steamForm).forEach(key => {
      this.ecDetCodes.push(this.steamForm[key].code);
    });
  }

  public updateData() {
    Tsrv.readPlcData(this.ecDetCodes).then(res => {
      if (typeof res !== 'boolean') {
        this.boilers.forEach(boiler => {
          Object.keys(boiler).forEach(key => {
            if (
              key === 'controlButtons' ||
              key === 'feedPump' ||
              key === 'sensors'
            ) {
              Object.keys(boiler[key]).forEach(code => {
                boiler[key][code].value = res[boiler[key][code].code].v;
              });
            } else {
              boiler[key].value = res[boiler[key].code].v;
            }
          });
        });
        Object.keys(this.steamForm).forEach(key => {
          this.steamForm[key].value = res[this.steamForm[key].code].v;
        });
      }
    });
  }

  handleStart(index: number) {
    const boiler = this.boilers[index];
    const d = [{ ecDetCode: boiler.controlButtons.start.code, value: '1' }];
    Tsrv.writePlcData(d).then(_ => {
      Tsrv.readPlcData([boiler.controlButtons.start.code]).then(res => {
        if (typeof res !== 'boolean') {
          boiler.controlButtons.start.value =
            res[boiler.controlButtons.start.code].v;
        }
      });
    });
  }

  handleStop(index: number) {
    const boiler = this.boilers[index];
    const d = [{ ecDetCode: boiler.controlButtons.stop.code, value: '2' }];
    Tsrv.writePlcData(d).then(_ => {
      Tsrv.readPlcData([boiler.controlButtons.stop.code]).then(res => {
        if (typeof res !== 'boolean') {
          boiler.controlButtons.stop.value =
            res[boiler.controlButtons.stop.code].v;
        }
      });
    });
  }

  handleReset(index: number) {
    const boiler = this.boilers[index];
    const d = [{ ecDetCode: boiler.controlButtons.reset.code, value: '3' }];
    Tsrv.writePlcData(d).then(_ => {
      Tsrv.readPlcData([boiler.controlButtons.reset.code]).then(res => {
        if (typeof res !== 'boolean') {
          boiler.controlButtons.reset.value =
            res[boiler.controlButtons.reset.code].v;
        }
      });
    });
  }

  handleMute(index: number) {
    const boiler = this.boilers[index];
    const d = [{ ecDetCode: boiler.controlButtons.mute.code, value: '4' }];
    Tsrv.writePlcData(d).then(_ => {
      Tsrv.readPlcData([boiler.controlButtons.mute.code]).then(res => {
        if (typeof res !== 'boolean') {
          boiler.controlButtons.mute.value =
            res[boiler.controlButtons.mute.code].v;
        }
      });
    });
  }

  handleFeedPumpStart(index: number) {
    const boiler = this.boilers[index];
    const d = [{ ecDetCode: boiler.feedPump.status.code, value: '100' }];
    Tsrv.writePlcData(d);
  }

  handleFeedPumpStop(index: number) {
    const boiler = this.boilers[index];
    const d = [{ ecDetCode: boiler.feedPump.status.code, value: '101' }];
    Tsrv.writePlcData(d);
  }

  handleFeedPumpAuto(index: number) {
    const boiler = this.boilers[index];
    const d = [{ ecDetCode: boiler.feedPump.mode.code, value: '102' }];
    Tsrv.writePlcData(d);
  }

  handleFeedPumpManual(index: number) {
    const boiler = this.boilers[index];
    const d = [{ ecDetCode: boiler.feedPump.mode.code, value: '103' }];
    Tsrv.writePlcData(d);
  }

  // 蒸汽表单失焦事件处理
  public handleSteamBlur(field: string) {
    const oldValue = this.steamForm[field].value;
    const newValue = this.steamForm[field].value;
    // if (oldValue !== newValue) {
    // 调用接口更新
    // this.updateParameter(`STEAM_${field.toUpperCase()}`, newValue);
    const d = [
      { ecDetCode: this.steamForm[field].code, value: newValue.toString() }
    ];
    Tsrv.writePlcData(d).then(_ => {
      // 读取数据
      Tsrv.readPlcData([this.steamForm[field].code]).then(res => {
        if (typeof res !== 'boolean') {
          this.steamForm[field].value = res[this.steamForm[field].code].v;
        }
      });
    });
    // }
  }

  // 蒸汽自动开关切换事件
  public handleSteamSwitchChange(
    param: N_BoilerMonitor.TankParameter,
    field: string
  ) {
    // 自动模式下禁用手动开关
    if (param.value && field === 'autoSwitch') {
      this.steamForm.valveSwitch.value = false;
    }
    const d = [{ ecDetCode: param.code, value: param.value.toString() }];
    Tsrv.writePlcData(d).then(_ => {
      // 读取数据
      Tsrv.readPlcData([param.code]).then(res => {
        if (typeof res !== 'boolean') {
          this.steamForm[field].value = res[param.code].v;
        }
      });
    });
  }
}
</script>

<style lang="scss" scoped>
.boiler-control {
  padding: 20px;

  .boiler-card {
    margin-bottom: 16px;

    ::v-deep .ivu-card-head {
      background: #f8f8f9;
    }

    .title-text {
      font-size: 16px;
      font-weight: bold;
      text-align: center;
    }

    .status-content {
      min-height: 240px;
      font-size: 14px;

      p {
        margin: 10px 0;
        color: #666;
      }

      .status-details {
        margin: 10px 0;
        padding: 10px 0;
        background: #f8f8f9;
        border-radius: 4px;

        .status-row {
          display: flex;
          align-items: center;
          margin-bottom: 8px;
          flex-wrap: wrap;

          span {
            margin-right: 5px;
          }

          .ivu-tag {
            margin-right: 10px;
          }
        }

        .sensor-status {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 8px;

          .sensor-item {
            display: flex;
            align-items: center;

            span {
              margin-right: 5px;
              white-space: nowrap;
            }
          }
        }
      }

      .btn-group {
        margin-top: 15px;
        display: flex;
        justify-content: space-around;
      }
    }
  }

  .quadrant-title {
    font-size: 16px;
    font-weight: bold;
    padding: 8px 12px;
    background: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 4px 4px 0 0;
    margin-bottom: -1px;
  }

  .grid-form {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    height: 100%;
    .form-item {
      padding-left: 20px;
    }
  }
}
</style>
